/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

#include "../../../common/data_utils.h"
#include "kernel_tiling/kernel_tiling.h"
#include "tiling/platform/platform_ascendc.h"
#include "../testcase_params.h"
#include "matmul_callback_custom_tiling.h"
#ifndef ASCENDC_CPU_DEBUG
#include "acl/acl.h"
#else
#include "tikicpulib.h"
#endif

int64_t CompareResult(void* outputData, const int64_t outSize)
{
    void* goldenData;
#ifdef ASCENDC_CPU_DEBUG
    goldenData = (uint8_t*)AscendC::GmAlloc(outSize);
#else
    CHECK_ACL(aclrtMallocHost((void**)(&goldenData), outSize));
#endif
    size_t goldenSize = outSize;
    bool ret = ReadFile("../output/golden.bin", goldenSize, goldenData, goldenSize);
    if (ret) {
        printf("ReadFile golden success!\n");
    } else {
#ifdef ASCENDC_CPU_DEBUG
        AscendC::GmFree((void*)goldenData);
#else
        CHECK_ACL(aclrtFreeHost(goldenData));
#endif
        return -1;
    }
    constexpr float EPS = 1e-4;
    int64_t wrongNum = 0;
    int64_t maxPrintNums = 10;  // limited print nums
    for (int i = 0; i < outSize / sizeof(float); i++) {
        float a = ((float*)outputData)[i];
        float b = ((float*)goldenData)[i];
        float ae = std::abs(a - b);
        float re = ae / abs(b);
        if (ae > EPS && re > EPS) {
            printf("CompareResult index %d failed output is %lf, golden is %lf\n", i, a, b);
            wrongNum++;
        }
        if (wrongNum > maxPrintNums) {
            break;
        }
    }
#ifdef ASCENDC_CPU_DEBUG
    AscendC::GmFree((void*)goldenData);
#else
    CHECK_ACL(aclrtFreeHost(goldenData));
#endif
    return wrongNum;
}

int32_t main(int32_t argc, char* argv[])
{
    constexpr TestcaseParams CALLBACK_CASE = {128*24, 128, 512, 24, true};
    const char* socVersion = SOC_VERSION;
    auto ascendcPlatform = platform_ascendc::PlatformAscendCManager::GetInstance(socVersion);

    int32_t blockDim = CALLBACK_CASE.blockDim;
    bool isBias = CALLBACK_CASE.isBias;
    int32_t M = CALLBACK_CASE.m;
    int32_t N = CALLBACK_CASE.n;
    int32_t K = CALLBACK_CASE.k;

    size_t aFileSize = M * K * sizeof(uint16_t);   // uint16_t represent half
    size_t bFileSize = K * N * sizeof(uint16_t);  // uint16_t represent half
    size_t biasFileSize = N * sizeof(float);
    size_t cFileSize = M * N * sizeof(float);
    size_t offsetListSize = 50 * sizeof(uint64_t);
    size_t userWorkspaceSize = 0;
    size_t systemWorkspaceSize = static_cast<size_t>(ascendcPlatform->GetLibApiWorkSpaceSize());
    size_t workspaceSize = userWorkspaceSize + systemWorkspaceSize;
    size_t tilingFileSize = sizeof(TCubeTiling);
    int64_t wrongNum = -1;

#ifdef ASCENDC_CPU_DEBUG
    uint8_t* a = (uint8_t*)AscendC::GmAlloc(aFileSize);
    uint8_t* b = (uint8_t*)AscendC::GmAlloc(bFileSize);
    uint8_t* bias = (uint8_t*)AscendC::GmAlloc(biasFileSize);
    uint8_t* c = (uint8_t*)AscendC::GmAlloc(cFileSize);
    uint8_t* offsetListT = (uint8_t*)AscendC::GmAlloc(offsetListSize);
    uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(workspaceSize);
    uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tilingFileSize);

    ReadFile("../input/x1_gm.bin", aFileSize, a, aFileSize);
    ReadFile("../input/x2_gm.bin", bFileSize, b, bFileSize);
    ReadFile("../input/offset_gm.bin", offsetListSize, offsetListT, offsetListSize);
    ReadFile("../input/bias_gm.bin", biasFileSize, bias, biasFileSize);
    MatmulCallbackTiling::GenerateTiling(socVersion, M, N, K, blockDim, isBias, tiling);
    memcpy_s(tiling, tilingFileSize, tiling, tilingFileSize);

    ICPU_RUN_KF(matmul_callback_custom, blockDim, a, b, bias, c, offsetListT, workspace, tiling);

    WriteFile("../output/output.bin", c, cFileSize);

    wrongNum = CompareResult(c, cFileSize);

    AscendC::GmFree((void*)a);
    AscendC::GmFree((void*)b);
    AscendC::GmFree((void*)c);
    AscendC::GmFree((void*)offsetListT);
    AscendC::GmFree((void*)workspace);
    AscendC::GmFree((void*)tiling);
#else
    CHECK_ACL(aclInit(nullptr));
    aclrtContext context;
    int32_t deviceId = 0;
    CHECK_ACL(aclrtSetDevice(deviceId));
    CHECK_ACL(aclrtCreateContext(&context, deviceId));
    aclrtStream stream = nullptr;
    CHECK_ACL(aclrtCreateStream(&stream));

    uint8_t* aHost;
    uint8_t* aDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&aHost), aFileSize));
    CHECK_ACL(aclrtMalloc((void **)&aDevice, aFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/x1_gm.bin", aFileSize, aHost, aFileSize);
    CHECK_ACL(aclrtMemcpy(aDevice, aFileSize, aHost, aFileSize,
                          ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* bHost;
    uint8_t* bDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&bHost), bFileSize));
    CHECK_ACL(aclrtMalloc((void **)&bDevice, bFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/x2_gm.bin", bFileSize, bHost, bFileSize);
    CHECK_ACL(aclrtMemcpy(bDevice, bFileSize, bHost, bFileSize,
                          ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* biasHost;
    uint8_t* biasDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&biasHost), biasFileSize));
    CHECK_ACL(aclrtMalloc((void **)&biasDevice, biasFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/bias_gm.bin", biasFileSize, biasHost, biasFileSize);
    CHECK_ACL(aclrtMemcpy(biasDevice, biasFileSize, biasHost, biasFileSize,
                          ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* offsetListHost;
    uint8_t* offsetListDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&offsetListHost), offsetListSize));
    CHECK_ACL(aclrtMalloc((void **)&offsetListDevice, offsetListSize,
                          ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/offset_gm.bin", offsetListSize, offsetListHost, offsetListSize);
    CHECK_ACL(aclrtMemcpy(offsetListDevice, offsetListSize, offsetListHost, offsetListSize,
                          ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* workspaceHost;
    uint8_t* workspaceDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&workspaceHost), workspaceSize));
    CHECK_ACL(aclrtMalloc((void **)&workspaceDevice, workspaceSize,
                          ACL_MEM_MALLOC_HUGE_FIRST));

    uint8_t* tilingHost;
    uint8_t* tilingDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&tilingHost), tilingFileSize));
    CHECK_ACL(aclrtMalloc((void **)&tilingDevice, tilingFileSize,
                          ACL_MEM_MALLOC_HUGE_FIRST));
    MatmulCallbackTiling::GenerateTiling(socVersion, M, N, K, blockDim, isBias, tilingHost);
    CHECK_ACL(aclrtMemcpy(tilingHost, tilingFileSize, tilingHost,
                          tilingFileSize, ACL_MEMCPY_HOST_TO_HOST));
    CHECK_ACL(aclrtMemcpy(tilingDevice, tilingFileSize, tilingHost,
                          tilingFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* cHost;
    uint8_t* cDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&cHost), cFileSize));
    CHECK_ACL(aclrtMalloc((void **)&cDevice, cFileSize, ACL_MEM_MALLOC_HUGE_FIRST));

    matmul_callback_custom_do(blockDim, stream, aDevice, bDevice, biasDevice, cDevice, offsetListDevice, workspaceDevice, tilingDevice);
    CHECK_ACL(aclrtSynchronizeStream(stream));

    CHECK_ACL(aclrtMemcpy(cHost, cFileSize, cDevice, cFileSize, ACL_MEMCPY_DEVICE_TO_HOST));
    WriteFile("../output/output.bin", cHost, cFileSize);

    wrongNum = CompareResult(cHost, cFileSize);

    CHECK_ACL(aclrtFree(aDevice));
    CHECK_ACL(aclrtFreeHost(aHost));

    CHECK_ACL(aclrtFree(bDevice));
    CHECK_ACL(aclrtFreeHost(bHost));

    CHECK_ACL(aclrtFree(biasDevice));
    CHECK_ACL(aclrtFreeHost(biasHost));

    CHECK_ACL(aclrtFree(cDevice));
    CHECK_ACL(aclrtFreeHost(cHost));

    CHECK_ACL(aclrtFree(offsetListDevice));
    CHECK_ACL(aclrtFreeHost(offsetListHost));

    CHECK_ACL(aclrtFree(workspaceDevice));
    CHECK_ACL(aclrtFreeHost(workspaceHost));

    CHECK_ACL(aclrtFree(tilingDevice));
    CHECK_ACL(aclrtFreeHost(tilingHost));

    CHECK_ACL(aclrtDestroyStream(stream));
    CHECK_ACL(aclrtDestroyContext(context));
    CHECK_ACL(aclrtResetDevice(deviceId));
    CHECK_ACL(aclFinalize());
#endif
    if (wrongNum != 0) {
        printf("test failed!\n");
    } else {
        printf("test pass!\n");
    }
    return 0;
}